package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivitySmsWaitBinding
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.utils.helper.TiyendeProcessHelper

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/25 18:45
 * @Annotation：SMS 等待
 */
class TiyendeSmsWaitActivity: CommonActivity() {
    lateinit var binding: TiyendeActivitySmsWaitBinding
    //等待时长
    private var countdown = 15
    private var countdownTimer: MyCountDownTimer? = null

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivitySmsWaitBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnVisibility(View.INVISIBLE)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitleVisibility(View.GONE)

        val showKey = getString(R.string.tiyende_loan_apply_wait_sms)
        val showText = String.format(getString(R.string.tiyende_loan_apply_wait_desc_value),showKey)
        val spString = SpannableString(showText)
        val start = showText.indexOf(showKey)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF3ED9AB")), start, start + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(StyleSpan(Typeface.BOLD), start, start + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        binding.loanApplyWaitTips.text =spString
    }

    override fun initTiyendeListener() {
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("SMS Preview Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"SMS Preview Page")
        }
    }

    override fun loadTiyendeData() {
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: TiyendeSmsWaitActivity, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showUploadSmsDataTipsText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showUploadSmsDataComplete()
        }
    }

    /**
     * 设置文本
     */
    @SuppressLint("SetTextI18n")
    private fun showUploadSmsDataTipsText(){
        binding.applySmsDataCountdown.text = "$countdown"
        showApplySmsDataStepStatusView()
    }

    /**
     * 倒计时完成
     */
    private fun showUploadSmsDataComplete(){
        showTiyendeLoading()
        //刷新主流程
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
    }

    /**
     *旋转动画
     */
    private fun getApplySmsDataAnimation(): Animation {
        // 创建一个旋转动画对象，从当前的角度旋转到指定的角度，持续时间为1000毫秒
        val rotateAnimation = RotateAnimation(0F, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        rotateAnimation.setDuration(1000L) // 设置动画持续时间
//        rotateAnimation.fillAfter = false // 动画执行完后保持结束状态
        rotateAnimation.isFillEnabled = true;
        rotateAnimation.fillBefore = false;
        rotateAnimation.setRepeatCount(Animation.INFINITE); // 设置动画重复次数
        return rotateAnimation
    }

    /**
     * 显示状态
     */
    private fun showApplySmsDataStepStatusView(){
        if (countdown > 10){
            binding.imgLoadApplyWaitStepIcon1.setImageResource(R.mipmap.tiyende_loan_apply_wait_step2_icon)
            binding.imgLoadApplyWaitStepIcon2.setImageResource(R.mipmap.tiyende_loan_apply_wait_step3_icon)
            binding.imgLoadApplyWaitStepIcon3.setImageResource(R.mipmap.tiyende_loan_apply_wait_step3_icon)
            return
        }

        if (countdown > 5){
            binding.imgLoadApplyWaitStepIcon1.setImageResource(R.mipmap.tiyende_loan_apply_wait_step1_icon)
            binding.imgLoadApplyWaitStepIcon2.setImageResource(R.mipmap.tiyende_loan_apply_wait_step2_icon)
            binding.imgLoadApplyWaitStepIcon3.setImageResource(R.mipmap.tiyende_loan_apply_wait_step3_icon)
            return
        }
        binding.imgLoadApplyWaitStepIcon1.setImageResource(R.mipmap.tiyende_loan_apply_wait_step1_icon)
        binding.imgLoadApplyWaitStepIcon2.setImageResource(R.mipmap.tiyende_loan_apply_wait_step1_icon)

        if (countdown >= 2){
            binding.imgLoadApplyWaitStepIcon3.setImageResource(R.mipmap.tiyende_loan_apply_wait_step2_icon)
            return
        }
        binding.imgLoadApplyWaitStepIcon3.setImageResource(R.mipmap.tiyende_loan_apply_wait_step1_icon)
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED -> {
                hiddenTiyendeLoading()
                //需要校验 WhatsApp 或 SMS
                if (TiyendeProcessHelper.isTiyendeAuthenticationCheckWhatsApp() || TiyendeProcessHelper.isTiyendeAuthenticationCheckSMS()){
//                    CheckAct.start(this)
                } else {
//                    val pName = getProductName()
//                    val pToken = getProductToken()
//                    ActivityOrderDetails.start(this, pName, pToken)
                }
                finish()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_SMS_PREVIEW_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_SMS_PREVIEW_END)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}